<?php
namespace App\Common\Ai;
use App\Common\Utill\Utills;
use App\Http\Controllers\Common\UploadsController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WenShenPicture
{
    protected static $appId = 'de6131de';
    protected static $apiSecret = 'YjI2OWIzY2UwOWM4MGQ0NDNhZjkzMzUz';
    protected static $apiKey = '07b24a09cd452a06fc634a40abebb5a2';

    protected static $hostUrl='https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti';

    public function index()
    {
        //填入相关参数
        $addr = self::$hostUrl;
        $appId = self::$appId;
        $apiKey = self::$apiKey;
        $apiSecret = self::$apiSecret;
        //调用结果鉴权
        $authUrl = $this->assembleAuthUrl("POST", $addr, $apiKey, $apiSecret);
        $width = 640;
        $height = 480;
        $content = "生成发稿相关的图片";
        $paramData['header'] = array('app_id'=>$appId);
        $paramData['parameter'] = array(
            'chat'=>array(
                'domain'=>'general',
                'width'=>$width,
                'height'=>$height
            )
        );
        $paramData['payload']= array(
            'message'=>array(
                'text'=>array(
                    array(
                        'role'=>'user',
                        'content'=>$content
                    )
                )
            )
        );
        $imageData = Utills::postCurl($authUrl,$paramData);
        $imageDataLog = $imageData;
        if($imageData['header']['code'] == 0){
            unset($imageDataLog['payload']['choices']['text'][0]['content']);
            Log::info("文字生成图片",$imageDataLog);
            $imageBase = $imageData['payload']['choices']['text'][0]['content'];
            $imageUrl = $this->imgBase64Decode($imageBase,false,true);
            $postData['keyword'] = $content;
            $postData['thumbs'] = $imageUrl;
            $postData['created_at'] = date("Y-m-d H:i:s");
            $postData['updated_at'] = date("Y-m-d H:i:s");
            DB::table("pd_ai_images")->insert($postData);
            exit();
        }else{
            Log::error("文字生成图片-fail",$imageData);
            echo "error:".$imageData['header']['message'];
            exit();
        }
    }

    /**
     * 图片base64解码
     * @param string $base64_image_content 图片文件流
     * @param bool $isDelImage //是否删除原图片
     * @param bool $isUploadQiNiu //是否上传七牛云
     * @return bool|string
     */
    public function imgBase64Decode($base64_image_content = '',$isDelImage=false,$isUploadQiNiu=false){
        if(empty($base64_image_content)){
            return false;
        }
        $file_content = base64_decode($base64_image_content);
        //如果没指定目录,则保存在当前目录下
        $path = public_path('uploads/article');
        $file_path = $path."/".date('Ymd',time())."/";
        if(!is_dir($file_path)){
            //检查是否有该文件夹，如果没有就创建
            mkdir($file_path,0777,true);
        }
        $file_type = "png";
        $file_name = time().".{$file_type}";
        $new_file = $file_path.$file_name;
        if(file_exists($new_file)){
            //有同名文件删除
            @unlink($new_file);
        }
        if (file_put_contents($new_file, $file_content)){
            $newFileArr = explode("public",$new_file);
            $imageUrl = ltrim($newFileArr[1],"\\");
            $uploadStatus = true;
            if($isUploadQiNiu){
                //上传七牛云
                $uploadObj = new UploadsController();
                $uploadStatus =$uploadObj->imageTuQiniu($new_file,$imageUrl);
            }
            if($isDelImage && $uploadStatus){
                //删除本地
                @unlink($new_file);
            }
            return "/".$imageUrl;
        }
        return '';
    }

    /**
     * 鉴权参数
     * @param $method
     * @param $addr
     * @param $apiKey
     * @param $apiSecret
     * @return mixed|string
     */
    public function assembleAuthUrl($method, $addr, $apiKey, $apiSecret)
    {
        if ($apiKey == "" && $apiSecret == "") { // 不鉴权
            return $addr;
        }
        $ul = parse_url($addr); // 解析地址
        if ($ul === false) { // 地址不对，也不鉴权
            return $addr;
        }
        // // $date = date(DATE_RFC1123); // 获取当前时间并格式化为RFC1123格式的字符串
        $timestamp = time();
        $rfc1123_format = gmdate("D, d M Y H:i:s \G\M\T", $timestamp);
        // $rfc1123_format = "Mon, 31 Jul 2023 08:24:03 GMT";
        // 参与签名的字段 host, date, request-line
        $signString = array("host: " . $ul["host"], "date: " . $rfc1123_format, $method . " " . $ul["path"] . " HTTP/1.1");
        // 对签名字符串进行排序，确保顺序一致
        // ksort($signString);
        // 将签名字符串拼接成一个字符串
        $sgin = implode("\n", $signString);
        //print($sgin);
        // 对签名字符串进行HMAC-SHA256加密，得到签名结果
        $sha = hash_hmac('sha256', $sgin, $apiSecret, true);
        //print("signature_sha:\n");
        //print($sha);
        $signature_sha_base64 = base64_encode($sha);
        // 将API密钥、算法、头部信息和签名结果拼接成一个授权URL
        $authUrl = "api_key=\"$apiKey\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"$signature_sha_base64\"";
        // 对授权URL进行Base64编码，并添加到原始地址后面作为查询参数
        $authAddr = $addr . '?' . http_build_query(array(
                'host' => $ul['host'],
                'date' => $rfc1123_format,
                'authorization' => base64_encode($authUrl),
            ));
        return $authAddr;
    }


}
